import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';

// const router = useRouter();

const service = axios.create({
  baseURL: 'http://localhost:8080', // 根据实际后端地址修改
  timeout: 10000
  
})

// 请求拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      localStorage.clear()
      router.push('/login'); 
    }
    ElMessage.error(error.response?.data?.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service